from typing import Optional

from repo_index.codeblocks.parser.parser import CodeParser
from repo_index.codeblocks.parser.python import PythonParser
from repo_index.codeblocks.parser.java import JavaParser


def is_supported(language: str) -> bool:
    return language in ["python", "java", "typescript", "javascript"]


def create_parser(language: str, **kwargs) -> Optional[CodeParser]:
    if language == "python":
        return PythonParser(**kwargs)
    elif language == "java":
        from tree_sitter_languages import get_language

        java_language = get_language(language)
        parser = CodeParser(language=java_language, **kwargs)
        # Load Java queries manually
        parser.queries.extend(parser._build_queries('java.scm'))
        return parser
    else:
        return CodeParser(language="java", **kwargs)

    raise NotImplementedError(f"Language {language} is not supported.")
